package sdk.webview.fmc.com.fmcsdk.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.base.CommonAdapter;
import sdk.webview.fmc.com.fmcsdk.base.ViewHolder;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.view.FrameStyleColorButton;

/**
 * 设置声音
 */
public class SoundSettingAcitivity extends BaseActivity implements View.OnClickListener {

    TitleBar titlebar;

    ImageView soundItemSelectImageview;
    ListView soundRingtoneListview;
    LinearLayout soundItemRl;
    FrameStyleColorButton soundSureButton;
    private RingListAdapter adapter;
    private PhoneListener phoneListener;
    private String curUrl = "";
    private String musicName;
    private MediaPlayer mediaPlayer;
    private int curPosition = -1;
    private String type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sound_setting_acitivity;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        soundItemSelectImageview = (ImageView) findViewById(R.id.sound_item_select_imageview);
        soundRingtoneListview = (ListView) findViewById(R.id.sound_ringtone_listview);
        soundItemRl = (LinearLayout) findViewById(R.id.sound_item_rl);
        soundItemRl.setOnClickListener(this);
        soundSureButton = (FrameStyleColorButton) findViewById(R.id.sound_sure_button);
        soundSureButton.setOnClickListener(this);
        if (savedInstanceState != null) {
            curPosition = savedInstanceState.getInt("curposition", -1);
            curUrl = savedInstanceState.getString("cururl", "");
        }
        type = getIntent().getStringExtra("type");
        if ("new".equalsIgnoreCase(type)) {//新任务
            titlebar.setTitle(getString(R.string.sound_setting_new));
            curUrl = sharedPrefs.getString(Constant.SOUND_NEW_URL, "");
            musicName = sharedPrefs.getString(Constant.SOUND_NEW_NAME, getString(R.string.sound_default));
        } else if ("grab".equalsIgnoreCase(type)) {//抢单设置
            titlebar.setTitle(getString(R.string.sound_setting_grab));
            curUrl = sharedPrefs.getString(Constant.SOUND_GRAB_URL, "");
            musicName = sharedPrefs.getString(Constant.SOUND_GRAB_NAME, getString(R.string.sound_default));
        }else if ("expire".equalsIgnoreCase(type)) {//过期设置
            titlebar.setTitle(getString(R.string.sound_expire_grab));
            curUrl = sharedPrefs.getString(Constant.SOUND_EXPIRE_URL, "");
            musicName = sharedPrefs.getString(Constant.SOUND_EXPIRE_NAME, getString(R.string.sound_default));
        }

        else {//消息设置
            titlebar.setTitle(getString(R.string.sound_setting_message));
            curUrl = sharedPrefs.getString(Constant.SOUND_MESSAGE_URL, "");
            musicName = sharedPrefs.getString(Constant.SOUND_MESSAGE_NAME, getString(R.string.sound_default));
        }
        //如果没有设置声音连接或者是FMC自带的声音连接，就属于系统默认
        if (TextUtils.isEmpty(curUrl) || curUrl.startsWith("android.resource")) {
            soundItemSelectImageview.setImageResource(R.mipmap.item_selected);
        } else {
            soundItemSelectImageview.setImageResource(R.mipmap.item_normal);
        }
        adapter = new RingListAdapter(context, getRingList(), R.layout.sound_item);
        soundRingtoneListview.setAdapter(adapter);
        //监听手机来电
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        phoneListener = new PhoneListener();
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        soundRingtoneListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Record record = (Record) parent.getItemAtPosition(position);
                curUrl = record.getString("uri");
                musicName = record.getString("title");
                startPlay(curUrl, -1);
                soundItemSelectImageview.setImageResource(R.mipmap.item_normal);
                adapter.notifyDataSetChanged();
            }
        });
    }

    //获取系统自带铃声列表
    public List<Record> getRingList() {
        List<Record> list = new ArrayList<Record>();
        RingtoneManager manager = new RingtoneManager(context);
        manager.setType(RingtoneManager.TYPE_RINGTONE);
        Cursor cursor = null;
        try {
            cursor = manager.getCursor();
            while (cursor.moveToNext()) {
                Record record = new Record(null);
                String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
                String uri = manager.getRingtoneUri(cursor.getPosition()).toString();
                record.setValue("title", title);
                record.setValue("uri", uri);
                list.add(record);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("SoundSettingActivity", e);
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return list;
    }


    public class RingListAdapter extends CommonAdapter<Record> {

        public RingListAdapter(Context context, List<Record> datas, int layoutId) {
            super(context, datas, layoutId);
        }

        @Override
        public void convert(ViewHolder holder, Record record, int position) {
            TextView title_tv = holder.getView(R.id.sound_item_name_textview);
            title_tv.setText(record.getString("title"));
            ImageView select_iv = holder.getView(R.id.sound_item_select_imageview);
            if (record.getString("uri").equalsIgnoreCase(curUrl)) {
                select_iv.setImageResource(R.mipmap.item_selected);
            } else {
                select_iv.setImageResource(R.mipmap.item_normal);
            }
        }
    }

    public class PhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            if (state == TelephonyManager.CALL_STATE_RINGING || state == TelephonyManager.CALL_STATE_OFFHOOK) {
                pausePlay();
            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                rePlay();
            }
        }
    }

    private void startPlay(String url, int position) {
        Uri uri = Uri.parse(url);
        startPlay(uri, position);
    }

    private void startPlay(Uri uri, int position) {
        if (uri == null) {
            return;
        }
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(context, uri);
            if (position != -1) {
                mediaPlayer.seekTo(position);
            }
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            logger.warn("SoundSettingActivity", e);
        }
    }

    private void pausePlay() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            curPosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
        }
    }

    private void rePlay() {
        if (curPosition != -1 && !TextUtils.isEmpty(curUrl)) {
            if (mediaPlayer == null) {
                startPlay(curUrl, curPosition);
            } else {
                mediaPlayer.start();
            }
        }
    }

    private void destoyPlay() {
        if (phoneListener != null) {
            TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            manager.listen(phoneListener, 0);
            phoneListener = null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.sound_sure_button){
            if ("new".equalsIgnoreCase(type)){
                sharedPrefs.edit().putString(Constant.SOUND_NEW_URL,curUrl).apply();
                sharedPrefs.edit().putString(Constant.SOUND_NEW_NAME,musicName).apply();

            } else if ("grab".equalsIgnoreCase(type)){
                sharedPrefs.edit().putString(Constant.SOUND_GRAB_URL,curUrl).apply();
                sharedPrefs.edit().putString(Constant.SOUND_GRAB_NAME,musicName).apply();
            }else if ("expire".equalsIgnoreCase(type)){
                sharedPrefs.edit().putString(Constant.SOUND_EXPIRE_URL,curUrl).apply();
                sharedPrefs.edit().putString(Constant.SOUND_EXPIRE_NAME,musicName).apply();
            }
            else{
                sharedPrefs.edit().putString(Constant.SOUND_MESSAGE_URL,curUrl).apply();
                sharedPrefs.edit().putString(Constant.SOUND_MESSAGE_NAME,musicName).apply();
            }
            Intent intent = new Intent();
            intent.putExtra("name",musicName);
            setResult(RESULT_OK,intent);
            finish();

        }else if (v.getId()==R.id.sound_item_rl){
            int language = sharedPrefs.getInt("lang", 0);
            if ("grab".equalsIgnoreCase(type)) {
                if (language==2){
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.newgrab_cht;
                }else {
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.newgrab;
                }
            } else if ("new".equalsIgnoreCase(type)){
                if (language==2){
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.newtask_cht;
                }else {
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.newtask;
                }
            }else if ("expire".equalsIgnoreCase(type)){
                if (language==2){
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.expire_cht;
                }else {
                    curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.expire;
                }
            }

            else {
                curUrl = "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify;
            }
            musicName = getString(R.string.sound_default);
            startPlay(Uri.parse(curUrl),-1);
            soundItemSelectImageview.setImageResource(R.mipmap.item_selected);
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (curPosition != -1){
            outState.putInt("curposition",curPosition);
        }
        if (!TextUtils.isEmpty(curUrl)){
            outState.putString("cururl",curUrl);
        }
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onPause() {
        super.onPause();
        pausePlay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        rePlay();
    }
    @Override
    protected void onDestroy() {
        destoyPlay();
        super.onDestroy();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }
}